<template>
  <div class="content-outer">
    <Block class="content-head">
      <BiForm>
        <BiFormItem label="用户ID">
          <template slot="content">
            <el-input
              v-model="requestData.member_id"
              placeholder="请输入用户ID"
            />
          </template>
        </BiFormItem>
        <!-- <miniAppSelect
          :is-resize="isResize"
          :multiple="true"
          @result="miniAppResult"
        /> -->
        <DateSelect
          label="观看广告时间"
          :default-value="[requestData.event_start_time,requestData.event_end_time]"
          :is-resize="isResize"
          :clearable="false"
          @result="resultDate"
        />

        <div class="search-item">
          <el-select
            v-model="seqPlayletValue"
            class="select-label"
            style="width:110px;"
            @change="seqPlayletChange"
          >
            <el-option
              v-for="(item) in seqPlayletList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            > </el-option>
          </el-select>
          <span
            v-if="seqPlayletValue=='playlet'"
            style="width:100%;"
          >
            <selectPlaylet
              :type="seqPlayletValue"
              :is-resize="seqPlayletIsResize"
              :multiple="true"
              :reserve="false"
              @result="seqPlayletResult"
            />
          </span>
          <label
            v-else-if="seqPlayletValue=='mainPlaylet'"
            style="width:100%;"
          >
            <selectPlaylet
              :type="seqPlayletValue"
              :is-resize="seqPlayletIsResize"
              :multiple="true"
              :reserve="false"
              @result="seqPlayletResult"
            />
          </label>
          <div
            v-else-if="seqPlayletValue=='versionPlaylet'"
            style="width:100%;"
          >
            <selectPlaylet
              :type="seqPlayletValue"
              :is-resize="seqPlayletIsResize"
              :multiple="true"
              :reserve="false"
              @result="seqPlayletResult"
            />
          </div>
        </div>
        <DateSelect
          label="染色时间"
          :is-resize="isResize"
          @result="resultDateSeq"
        />
        <BiFormItem label="渠道名称">
          <template slot="content">
            <el-select
              ref="channel"
              v-model="requestData.channel_id"
              remote
              clearable
              :remote-method="remoteMethod"
              filterable
              placeholder="请输入渠道ID/名称"
              multiple
              collapse-tags
              @focus="mobileClearChannel"
              @hook:mounted="mobileClearChannel"
              @visible-change="mobileClearChannel"
              @change="onChannelChange"
            >
              <el-option
                v-for="item in channelList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </template>
        </BiFormItem>
        <BiFormItem>
          <template slot="button">
            <el-button
              style="margin-left: 10px"
              type="primary"
              :disabled="loading"
              :loading="loading"
              @click="startSearch"
            >查询</el-button>
            <el-button @click="reset">重置</el-button>
          </template>
        </BiFormItem>
      </BiForm>
    </Block>
    <Block class="content-table">
      <div class="action-box">
        <div class="left">
          仅记录抖音小程序-洋气剧院流量主收入数据
        </div>
        <div class="right">
          <div style="float:right;">
            <el-button
              style="margin-left:20px;"
              @click="exportList"
            >导出</el-button>
          </div>
        </div>
      </div>

      <div class="table-table">
        <BiTable
          :loading="loading"
          :data="tableData"
          size="medium"
          :column="tableColums"
          fixed="sticky"
          fixed-offset="50"
          pagination
          layout="total, prev, pager, next"
          :auto-scroll="false"
          :total="page_info.total"
          :page.sync="page_info.page"
          :show-summary="true"
          :summary-method="getSummaries"
          :limit.sync="page_info.page_size"
          @pagination="handlePageChange"
        >
          <template v-slot:mini_app_name="{ row }">
            <p>{{ row.mini_app_name }}
              <svg-icon
                v-if="row.app_type==1"
                icon-class="miniapp"
                class="imageIcon"
              />
              <svg-icon
                v-else
                icon-class="douyin"
                class="imageIcon"
              />
            </p>
            <p class="infoText">{{ row.mini_app_id }}</p>
          </template>
          <template v-slot:cost="{ row }">
            <template slot="label">
              活动状态
              <el-tooltip
                class="item"
                effect="dark"
                placement="top"
                popper-class="tooltipWidth"
              >
                <div slot="content">
                  <p>1. 当选择“展示”活动时，该活动可根据配置的模板显示在小程序端相应位置</p>
                  <p>2. 当选择“隐藏”活动时，则不显示在小程序端，但活动仍有效</p>
                </div>
                <i class="el-icon-question"></i>
              </el-tooltip>
            </template>
          </template>
        </BiTable>
      </div>
    </Block>

  </div>
</template>

<script>
import { ad_ecpm_list } from '@/api/adver'
import { exportData } from '@/api/order'
import { mapState, mapActions } from 'vuex'
import miniAppSelect from '@/common/component/form/miniAppSelect.vue'
import DateSelect from '@/common/component/form/dateSelect.vue'
import { formatNumber, numWay } from '@/utils/index'
import { commonData } from '@/api/common'
export default {
  name: 'Pays',
  components: {
    miniAppSelect,
    DateSelect
  },
  data() {
    return {
      formatNumber: formatNumber,
      numWay: numWay,
      seqPlayletList: [
        { label: '染色短剧', value: 'playlet' },
        { label: '染色合同', value: 'mainPlaylet' }
        // { label: '染色版本剧', value: 'versionPlaylet' }
      ],
      seqPlayletValue: 'playlet',
      isResize: false,
      seqPlayletIsResize: false,
      selectLoading: false,
      playletList: [],
      channelList: [],
      totalAmount: '',
      requestData: {
        mini_app_id: '',
        member_id: '',
        seq_playlet_id: [],
        seq_main_playlet_id: [],
        channel_id: [],
        event_start_time: this.$moment().format('YYYY-MM-DD'),
        event_end_time: this.$moment().format('YYYY-MM-DD'),
        seq_start_time: '',
        seq_end_time: ''
      },
      loading: false,
      page_info: {
        page: 1,
        page_size: 20,
        total: 0
      },
      tableData: [],
      tableColums: [
        {
          label: '用户ID',
          prop: 'member_id',
          minWidth: 120
        },
        {
          label: '小程序',
          prop: 'mini_app_name',
          minWidth: 150,
          slotScope: true
        },

        {
          label: '广告类型',
          prop: 'ad_type',
          render: (h, { row }) => {
            if (row.ad_type) {
              return <span>{row.ad_type}</span>
            } else {
              return <span>-</span>
            }
          },
          minWidth: 120
        },
        {
          label: '渠道/id',
          prop: 'channel_name',
          render: (h, { row }) => {
            if (row.channel_name) {
              return <span>{row.channel_name}/{row.channel_id}</span>
            } else {
              return <span>-</span>
            }
          }
        },
        {
          label: '染色短剧',
          prop: 'seq_playlet_title',
          render: (h, { row }) => {
            if (row.seq_playlet_title) {
              return <span>{row.seq_playlet_title}</span>
            } else {
              return <span>-</span>
            }
          }
        },
        {
          label: '染色合同',
          prop: 'seq_main_playlet_title',
          render: (h, { row }) => {
            if (row.seq_main_playlet_title) {
              return <span>{row.seq_main_playlet_title}</span>
            } else {
              return <span>-</span>
            }
          }
        },
        {
          label: '观看短剧',
          prop: 'playlet_title',
          render: (h, { row }) => {
            if (row.playlet_title) {
              return <span>{row.playlet_title}</span>
            } else {
              return <span>-</span>
            }
          }
        },
        {
          label: '观看短剧归属合同',
          prop: 'main_playlet_title',
          minWidth: 140,
          render: (h, { row }) => {
            if (row.main_playlet_title) {
              return <span>{row.main_playlet_title}</span>
            } else {
              return <span>-</span>
            }
          }
        },
        {
          label: '分销方',
          prop: 'distributor'
        },

        {
          label: '观看广告时间',
          prop: 'event_time',
          minWidth: 160,
          render: (h, { row }) => {
            if (row.event_time) {
              return (
                <span>
                  <p>{row.event_time}</p>
                </span>
              )
            }
          }
        },
        {
          label: '预估收益',
          prop: 'cost',
          minWidth: 100,
          renderHeader: (h, { row }) => {
            return (
              <div>
              预估收益
              </div>
            )
          },
          render: (h, { row }) => {
            return <span>{numWay(formatNumber(row.cost))} </span>
          }
        }
      ]
    }
  },
  computed: {
    ...mapState('common', ['miniAppList', 'commonDataList'])
  },
  mounted() {
    this.initData()
    this.$AccessReport.report('zhangyu-order', [this.$store.state.user.routerItem.name, '流量主管理'])
  },
  methods: {
    ...mapActions('common', ['requestMiniApp', 'requestCommonData']),
    ...mapActions('user', ['requestMiniApp']),
    async initData() {
      this.requestMiniApp()
      this.clickSearch()
    },
    mobileClearChannel(async) {
      this.$nextTick(() => {
        if (!async) {
          // ios 手机有延迟问题
          setTimeout(() => {
            const { channel } = this.$refs
            const input = channel.$el.querySelector('.el-input__inner')
            input.removeAttribute('readonly')
          }, 200)
        }
      })
    },
    seqPlayletResult(value) {
      if (this.seqPlayletValue === 'playlet') {
        this.requestData.seq_playlet_id = value
      } else if (this.seqPlayletValue === 'mainPlaylet') {
        this.requestData.seq_main_playlet_id = value
      } else if (this.seqPlayletValue === 'versionPlaylet') {
        this.requestData.seq_contract_playlet_id = value
      } else {
      }
    },
    seqPlayletChange(value) {
      this.requestData.seq_playlet_id = []
      this.requestData.seq_main_playlet_id = []
      this.seqPlayletIsResize = true
      setTimeout(() => {
        this.seqPlayletIsResize = false
      }, 200)
    },
    remoteMethod(query) {
      if (query !== '') {
        commonData({ type: 'channel', value: query, mini_app_id: localStorage.getItem('mini_app_id') ? localStorage.getItem('mini_app_id') : '' }).then((res) => {
          this.channelList = res.data.data
          this.channelList.unshift({
            label: '全选',
            value: '000'
          })
        })
      }
    },
    onChannelChange(value) {
      console.log(value)
      const activeList = []
      const allIndex = this.requestData.channel_id.indexOf('000')
      if (value.indexOf('000') != -1) {
        this.channelList.map((item) => {
          item.value != '000' ? activeList.push(item.value) : null
        })
        this.requestData.channel_id.splice(allIndex, 0)
        this.requestData.channel_id = activeList
      }
    },
    // 导出
    exportList() {
      const list = this.tableColums.map((item) => item.prop)
      list.push('channel_id')
      const data = {
        task_uri: `/api/admin/ad_ecpm/list`,
        auto_column: list,
        ...this.requestData,
        mini_app_id: this.requestData.mini_app_id.length > 0 ? this.requestData.mini_app_id : localStorage.getItem('mini_app_id') ? [localStorage.getItem('mini_app_id')] : []
      }
      exportData(data).then((res) => {
        if (res.status_code === 1) {
          this.$message.success(res.msg)
        }
      })
    },

    getSummaries(param) {
      const { columns, data } = param
      const sum = []
      columns.forEach((item, index) => {
        if (index === 0) {
          sum[index] = '汇总'
          return
        }
        if (item.property === 'cost') {
          sum[index] = formatNumber(this.totalAmount) + '元'
          return
        }
      })
      return sum
    },
    resultDateSeq(value) {
      this.requestData.seq_start_time = value.start_date
      this.requestData.seq_end_time = value.end_date
    },
    startSearch() {
      this.page_info.page = 1
      this.clickSearch()
    },
    miniAppResult(value) {
      this.requestData.mini_app_id = value
    },
    resultDate(value) {
      this.requestData.event_start_time = value.start_date
      this.requestData.event_end_time = value.end_date
    },
    clickSearch() {
      this.loading = true
      ad_ecpm_list({ ...this.requestData, ...this.page_info }).then((res) => {
        this.loading = false
        if (res.status_code === 1) {
          this.tableData = res.data.data
          this.page_info = res.data.page_info
          this.totalAmount = res.data.page_info.cost_total
        }
      }, errr => {
        this.loading = false
      })
    },
    reset() {
      this.isResize = true
      this.seqPlayletIsResize = true
      this.playletIsResize = true
      this.seqPlayletValue = 'playlet'
      setTimeout(() => {
        this.isResize = false
        this.seqPlayletIsResize = false
        this.playletIsResize = false
      }, 200)
      this.$set(this, 'requestData', {
        mini_app_id: '',
        member_id: '',
        seq_playlet_id: [],
        seq_main_playlet_id: [],
        channel_id: [],
        event_start_time: this.$moment().format('YYYY-MM-DD'),
        event_end_time: this.$moment().format('YYYY-MM-DD'),
        seq_start_time: '',
        seq_end_time: ''
      })
      this.$set(this, 'page_info', {
        page: 1,
        page_size: 20,
        total: 0
      })
    },
    handlePageChange(page) {
      this.page_info.page = page.page
      this.clickSearch()
    }
  }
}
</script>
  <style lang="scss" scoped>
::v-deep .el-tag.el-tag--info.el-tag--mini.el-tag--light {
  max-width: 130px;
}
.action-box {
  width: 100%;
}
.infoText {
  font-size: 12px;
  color: #999;
}
.redText {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #ff4d4f;
}
p {
  margin: 3px 0;
}
.game-name {
  display: flex;
  align-items: center;
}
</style>
